package com.hn658.base.message.backend.servlet;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.exception.ExceptionUtils;

import com.hn658.base.message.app.service.IAppInfoManager;
import com.hn658.base.message.app.service.IUserInfoManager;
import com.hn658.base.util.auth.AuthCookieEditor;
import com.hn658.base.util.constants.BaseContants;
import com.hn658.framework.logging.enums.LogCategory;
import com.hn658.framework.shared.exception.BaseException;
import com.hn658.framework.shared.exception.SystemException;
import com.hn658.framework.shared.exception.UnknowException;
import com.hn658.message.config.service.IBaseMessageConfig;
import com.hn658.user.itf.vo.AppInfoDTO;
import com.hn658.user.itf.vo.UserInfoDTO;

/**
 * 登录的servlet
 * @ClassName: LoginServlet
 * @author ztjie
 * @date 2014年9月2日 下午2:46:23
 */
public class IndexServlet extends AbstractServlet {

	private static final long serialVersionUID = 3599960399642760403L;
	
	private IBaseMessageConfig baseMessageConfig;
	
	private IAppInfoManager appInfoManager;
	
	private IUserInfoManager userInfoManager;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
   		super.init(config);
   		baseMessageConfig = ac.getBean(IBaseMessageConfig.class);
   		appInfoManager = ac.getBean(IAppInfoManager.class);
   		userInfoManager = ac.getBean(IUserInfoManager.class);
   	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 当前服务session中没有user对象,从cookie中初始化user到session中
		Cookie cookie = AuthCookieEditor.getCookie(request);
		try{
			if(cookie==null){
				forwardLogin(request, response);
				return;
			}
			UserInfoDTO loginUser = userInfoManager.validateCookie(baseMessageConfig.getAppId(), cookie.getValue());
			if(loginUser!=null){
				forwardIndex(request, response);
			}else{
				forwardLogin(request, response);
			}	
		}catch (Exception e){
			forwardError(request, response, e);
		}
	}

	public void forwardIndex(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/pages/index.jsp").forward(
				request, response);
	}

	public void forwardLogin(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		AppInfoDTO appInfo = appInfoManager.findCurrentAppInfo();
		response.sendRedirect(baseMessageConfig.getLoginUrl()+"?returnUrl="+URLDecoder.decode(appInfo.getUrl(), BaseContants.SYSTEM_CHAERSET));
	}
	
	public void forwardError(HttpServletRequest request,
			HttpServletResponse response, Exception e) throws ServletException, IOException {
		BaseException baseException = null;
		if (BaseException.class.isAssignableFrom(e.getClass())) {
			baseException = (BaseException) e;
		}else {
			logger.error(LogCategory.APPLICATION, e.getMessage(), e);
			SystemException systemException = this.convert(e);
			baseException = systemException;
		}
		final String errorMsg = messageCache
				.getMessage(baseException.getErrorCode());
		request.setAttribute("errorMsg", errorMsg);
		if (logger.isDebugEnabled()) {
			request.setAttribute("stackTrace", ExceptionUtils.getStackTrace(e));
		}
		request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(
				request, response);
	}
	
	private SystemException convert(Throwable target) {
		if (SystemException.class.isAssignableFrom(target.getClass())) {
			return (SystemException) target;
		}
		return new UnknowException(target.toString(), target);
	}
}
